<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/11/19
 * Time: 15:12
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/vest-list.css');
AppAsset::addCss($this,$base . '/app/css/bar-detail.css?V=0.0.4');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');

$model = new CommonHelper();
$baseUrlHead  = $model->getIp();

?>
<div class="detail-container" style="width: 74rem">
    <p class="top-title">基本信息</p>

    <div style="float: left">
        <p class="item-title"><span class="necessary-note">*</span>马甲名称</p>
        <input id="userName" class="input-row" maxlength="10" placeholder="请输入" value="<?= $user['user_nickname']?>">
    </div>

    <div class="clear"></div>

    <div style="float: left;">
        <p class="item-title"><span class="necessary-note">*</span>签名</p>
        <input id="userSign" class="input-row" placeholder="请输入" value="<?= $user['user_sign'] != "%Null%" ?$user['user_sign']:""?>" maxlength="30">
    </div>

    <div class="clear"></div>

    <p class="item-title"><span class="necessary-note">*</span>图片（最多9张）</p>
    <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file2" name="upload-file2" onchange="thumbImage(this)" style="display: none">
    <div class="image-container">
        <div id="imageChoose" class="image-item" onclick="showPic(0)">
            <img class="image-choose" src="<?= $base?>/app/images/dynamic/default-logo.png">
        </div>
    </div>

    <div class="clear"></div>

    <div class="button-div" style="margin-top: 1.67rem">保存</div>
</div>

<script>
    function setPhotos(photos){
        if(photos.length > 0 && photos != "%Null%"){
            var arr = photos.split(";");
            for(var index=0;index<arr.length;index++){
                var imgHtml = '<div class="image-item">'+
                    '<img class="image-delete" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_found_picture_close.png" onclick="deleteImage(this)">'+
                    '<img class="image-value" src="'+arr[index]+'">'+
                    '</div>';

                $(".image-container").append(imgHtml);

                if($(".image-value").length == photoMax)
                    $("#imageChoose").hide();
            }
        }
    }

    function deleteImage(view){
        $(view).parent().remove();
        if($(".image-value").length < photoMax)
            $("#imageChoose").show();
    }

    var updateUserController = {
        updateUserApi : "vest",
        //上下架酒吧
        updateUserFunc:function(){

            var userName = $("#userName").val();
            if(userName.length == 0){
                alert("请输入马甲名称");
                return;
            } else if(userName.length > 10) {
                alert("名称不能超过10个字");
            }

            var param = {
                user_id:'<?= $user['user_id']?>',
                user_name:userName
            };

            var userSign = $("#userSign").val();
            if(userSign.length > 0){
                param.sign = userSign;
            } else if(userSign.length > 30) {
                alert("个性签名不能超过30个字");
            } else {
                param.sign = "%Null%";
            }

            if($(".image-value").length > 0)
                param.photos = getImageValue();
            else
                param.photos = "%Null%";

            sendAjax(this.updateUserApi,"POST",param,true,function(res){
                var data = JSON.parse(res);
                if(data.code == 0)
                    alert('编辑成功');
                    window.location.reload();
            });
        }
    };

    function getImageValue(){
        var imageString = "";
        $(".image-value").each(function() {
            imageString +=$(this).attr("src") + ";";
        });
        var reg=/;$/gi;
        return imageString.replace(reg,"");
    }
</script>

<script>

    var photoMax = 9;
    $(function(){
        setPhotos('<?= $user['user_photos']?>');

        $(".button-div").click(function(){
            updateUserController.updateUserFunc();
        });

//选择图片点击事件
        $(".myClose").click(function(){
            closePic();
        });
        $(".select-img").click(function(){
            upload(this);
        });
        $(".upload-img").click(function(){
            uploadImage(this);
        });
        //选择图片结束
    });

    //点击图片来选择上传的图片
    function upload(button){
//        $(button).css('background-color','#77778F').css('color','white');
        var intputId = 'upload-file2';
        document.getElementById(intputId).click();
    }

    function showPic(){
        $('.choose-area').show();
    }

    function closePic(){
        $('.choose-area').hide();
        $('.pic-area').empty();
        if (!$('.pic-area img').length){
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        $('.upload').css('background-color','white').css('color','#A8A8A8');
        $('.select-img').css('background-color','white').css('color','#A8A8A8');
        //清除input file 的value,可以触发下次的onchange;
        $('#upload-file2').val('');

        $('.upload-img').css('background','white').prop('disabled',false);

    }
    //选择图片之后的操作

    //图片缩略图处理
    function thumbImage(input){
        //设置宽高比
        var w = 1;
        var h = 1;

        //再次点击上传时清除之前的截图操作
        if ($('.jcrop-holder').length){
            $('.pic-area').empty();
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        if (typeof (FileReader) != "undefined") {
            var regex = /(.jpg|.jpeg|.png)$/;
            $($(input)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
//                        var img = $(input).prev();
                        var img = $('#pic-area-img');
                        $(img).attr('src',e.target.result);
                        var realWidth;//真实的宽度
                        var realHeight;//真实的高度
                        //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
                        $("<img/>").attr("src", $(img).attr('src')).load(function() {
                            /*
                             如果要获取图片的真实的宽度和高度有三点必须注意
                             1、需要创建一个image对象：如这里的$("<img/>")
                             2、指定图片的src路径
                             3、一定要在图片加载完成后执行如.load()函数里执行
                             */
                            realWidth = this.width;
                            realHeight = this.height;
                            var width = $('.pic-area').css('width').split('p')[0];
                            var height = $('.pic-area').css('height').split('p')[0];
//                            console.log(realWidth,realHeight,width,height)
                            if(realWidth<width && realHeight<height){
                                $(img).css("width",realWidth+'px').css("height",realHeight+'px');
                            }else{
                                //如果真实的宽高比大于给定的宽高比就按照宽度100%显示
                                if(realWidth/realHeight >= width/height){
                                    $(img).css("width","99%").css("height","auto");
                                }
                                else{//如果小于给定的宽高比按照原尺寸显示
                                    $(img).css("width","auto").css("height","99%");
                                }
                            }
//                            console.log(realWidth,$(img).css("width").split('p')[0]);
                            var ratio = realWidth/$(img).css("width").split('p')[0];
//                            console.log(ratio)
                            $('#pic-area-img').show();
                            var jcrop_api;
                            $('#pic-area-img').Jcrop({
                                aspectRatio: w / h,
                                onSelect:uodateCoords,
                                setSelect:[0,0,600,600]
                            },function(){
                                jcrop_api = this;
                            });
                            function uodateCoords(c){
                                $('#x').val(c.x*ratio);
                                $('#y').val(c.y*ratio);
                                $('#w').val(c.w*ratio);
                                $('#h').val(c.h*ratio);
                            }
                            var jcropWidth =   $(img).css('width').split('p')[0];
                            var jcropHeight =   $(img).css('height').split('p')[0];
                            var marginLeft = (width-jcropWidth)/2;
                            var marginTop = (height-jcropHeight)/2;
//                            $('.jcrop-holder').css("margin-top",marginTop + 'px');
                            $('.jcrop-holder').css("margin-left",marginLeft + 'px');
//                            jcrop_api.setSelect([marginLeft,marginTop,336,336]);
                        });
                    }
                    reader.readAsDataURL(file[0]);
                }else {
                    alert(file[0].name + " is not a valid image file.");
                    return false;
                }
            })
        }else{
            alert("This browser does not support HTML5 FileReader.");
        }
    }
    //ajax 异步上传图片
    function uploadImage(button){
        //定义允许上传的图片格式 在前台就可以直接判断，不合法的格式将不会上传
        //尺寸限制

        var intputId = 'upload-file2';
        var limit = 8 * 1024 * 1024;

        var file = $('#'+intputId).get(0).files;

//            $($(button).parent().prev().children()[1]).get(0).files;
        var filetype = ['jpg','jpeg','png','gif'];
        if(file.length){
            var fi = file[0]; //得到文件信息
            //判断文件格式是否是图片 如果不是图片则返回false
            var index = fi.name.lastIndexOf('.');
            var fname = [fi.name.substring(0,index),fi.name.substring(index+1)];
            if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                alert('文件格式不支持');
                return ;
            }
            //实例化h5的fileReader
            var fr = new FileReader();
            fr.readAsDataURL(fi); //以base64编码格式读取图片文件
            fr.onload = function(frev){
                pic = frev.target.result; //得到结果数据

                //开始上传之前，预览图片
//                $('#img').attr('src',pic);
                //使用ajax 利用post方式提交数据
                var x = $('#x').val();
                var y= $('#y').val();
                var width= $('#w').val();
                var height= $('#h').val();
                if (width == 0 && height == 0){
                    alert('请选择图片');
                    return;
                }
                if(fi.size > limit){
                    alert("上传照片不得大于8M");
                    return;
                }

                $('.loading-area').show();
                $(button).css('background','#CCCCCC').prop('disabled',true);
                $.post(
                    'img-upload',
                    {
                        message:pic,
                        filename:fname[0],
                        filetype:fname[1].toLowerCase(),
                        filesize:fi.size,
                        x:x,
                        y:y,
                        width:width,
                        height:height,
                        limit:limit
                    },
                    function(data){
                        data = eval('('+data+')');
                        if(data.code == 1){
                            $('.loading-area').hide();
                            alert('上传失败');
                        }else if(data.code == 0){

                            var imgHtml = '<div class="image-item">'+
                                '<img class="image-delete" src="<?= $base?>/app/images/dynamic/rc_icon_seduce_dynamic_found_picture_close.png" onclick="deleteImage(this)">'+
                                '<img class="image-value" src="'+data.imgSrc+'">'+
                                '</div>';

                            $(".image-container").append(imgHtml);

                            if($(".image-value").length == photoMax)
                                $("#imageChoose").hide();

                            $('.loading-area').hide();
                            alert('上传成功');
                            closePic();
                        }else if(data.code == 2){
                            var size = parseInt(parseInt(data.size)/1000);
                            if (size>1000)
                                size = parseInt(size/1000) + 'M';
                            else
                                size += 'KB';
                            var msg = data.msg + ',当前图片尺寸为:' + size;
                            $('.loading-area').hide();
                            alert(msg);
                        }
                    }
                )
                    .fail(function(xhr,status,error){
//                    console.log(xhr,status,error)
                        $('.loading-area').hide();
                        alert('上传失败')
                    })
            }
        }else
            alert('请选择图片');
    }
</script>